const app = getApp()
Page({
    data: {
        lastX: 0, //滑动开始x轴位置
        lastY: 0, //滑动开始y轴位置
        currentGesture: 0, //标识手势
        year: 0,
        month: 0,
        days: ['一', '二', '三', '四', '五', '六', '日'],
        dateArr: [],
        lYear: '',
        isToday: 0,
        isTodayWeek: false,
        todayIndex: 0
    },
    onLoad: function() {
        let nowDate = new Date();        
        this.dateInit(nowDate.getFullYear(), nowDate.getMonth() + 1);
    },  
    dateInit: function(setYear, setMonth) {
        let setItems = (setYear, setMonth, lYear, dateArr) => {
            this.setData({
                year: setYear,
                month: setMonth,
                lYear: lYear,
                dateArr: dateArr
            })
        }
        wx.request({
            url: app.globalData.url + '/calendar',
            header: {
                'charset': 'utf-8',
                'content-type': 'application/json' // 默认值
            },
            method: 'POST',
            data: {
                year: setYear,
                month: setMonth
            },
            success: function(res) {                
                if (res.statusCode != 200) return;
                //待遍历的日历数组
                setItems(setYear, setMonth, res.data.l_year, res.data.dates)
            }
        })
    },
    lastMonth: function() {
        //全部时间的月份都是按0~11基准，显示月份才+1
        let year = this.data.month < 2 ? this.data.year - 1 : this.data.year;
        let month = this.data.month < 2 ? 12 : this.data.month - 1;
        this.setData({
            year: year,
            month: month
        })
        this.dateInit(year, month);
    },
    nextMonth: function() {
        //全部时间的月份都是按0~11基准，显示月份才+1
        let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
        let month = this.data.month > 11 ? 1 : this.data.month + 1;
        this.setData({
            year: year,
            month: month
        })
        this.dateInit(year, month);
    },
    //滑动开始事件
    handletouchtart: function(e) {
        this.data.lastX = e.touches[0].pageX
        this.data.lastY = e.touches[0].pageY
    },
    //滑动结束事件
    handletouchend: function(event) {
        if (this.data.currentGesture < 0) this.lastMonth();
        else if (this.data.currentGesture > 0) this.nextMonth();
        else return;
        this.data.currentGesture = 0;
    },
    //滑动移动事件
    handletouchmove: function(event) {
        var currentX = event.touches[0].pageX
        var currentY = event.touches[0].pageY
        var tx = currentX - this.data.lastX
        var ty = currentY - this.data.lastY
        //左右方向滑动
        if (Math.abs(tx) > Math.abs(ty)) {
            if (tx < 0)
                this.data.currentGesture = 1;
            else if (tx > 0)
                this.data.currentGesture = -1;
        }
    }
})